package com.ly.work.practice;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheTest {

    private static Map<String,Object> map = new HashMap<String,Object>(){
        {
            put("a","a");
            put("b","b");
            put("c","c");
            put("d","d");
        }
    };

    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = reentrantReadWriteLock.readLock();
    private static Lock writerLock = reentrantReadWriteLock.writeLock();

    public static void main(String[] args) {
        //声明连个线程集合
        List<Thread> readlist = new ArrayList<Thread>();
        List<Thread> writelist = new ArrayList<Thread>();

        for (int j = 0 ; j< 1000; j++) {
            //读线程
            Thread readthread = new Thread(() -> {
                try {
                    readLock.lock();
                    System.out.println(Thread.currentThread().getName() + "正在读取数据" + JSON.toJSONString(map));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    readLock.unlock();
                }

            });

            readlist.add(readthread);

            //写线程
            Thread writethread = new Thread(() -> {
                try {
                    writerLock.lock();
                    System.out.println(Thread.currentThread().getName() + "正在更新数据" );
                    map.put("a",Thread.currentThread().getName()+"a");
                    map.put("b",Thread.currentThread().getName()+"b");
                    map.put("c",Thread.currentThread().getName()+"c");
                    map.put("d",Thread.currentThread().getName()+"d");
                    System.out.println(Thread.currentThread().getName() + "更新数据完成"+JSON.toJSONString(map));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    writerLock.unlock();
                }
            });

            writelist.add(writethread);
        }


        for(int i = 0; i<readlist.size(); i++){
            readlist.get(i).start();
            writelist.get(i).start();

        }
    }


}
